package com.serverclient.cglib.beanregister;

import java.lang.reflect.Method;
import java.util.Map;

import com.serverclient.cglib.bean.HttpService;
import com.serverclient.cglib.enums.HttpMethod;
import com.serverclient.cglib.service.ServerCglibService;
import com.serverclient.utility.HttpUtility;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * 方法拦截器
 */
public class ServiceMethodInterceptor implements MethodInterceptor {
	/**
	 * 第一个参数为真实的实例
	 * 第二个参数为被拦截的方法
	 * 第三个参数为调用被拦截方法时传递的参数
	 * 第四个参数为代理方法
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		if(method.getName().equals("request") && args != null){
			HttpService httpService = ServerCglibService.methodMap.get(args[0].toString());
			Map<String,String> header = (Map<String,String>)args[2];
			if(HttpMethod.GET.equals(httpService.getHttpMethod())) {
				Map<String,String> param = (Map<String,String>)args[1];
				return HttpUtility.get(httpService.getUrl(), param, header);
			}else {
				return HttpUtility.post(httpService.getUrl(), args[1], header);
			}
		}
		//如果不是需要被拦截的方法，需要调用真实对象的真实方法
		return proxy.invokeSuper(obj, args);
	}
}
